package cn.kailangtu.commontools.socket;

import android.os.SystemClock;
import android.util.Log;

import java.io.IOException;

import cn.kailangtu.commontools.CommonUtils;

public class TemperatureManager {

    private static TemperatureManager instance = null;

    public static TemperatureManager getInstance(){
        if(instance == null)
        {
            instance = new TemperatureManager();
        }
        return instance;
    }

    private TemperatureManager(){
        initSocketClient();
    }

    private SocketClient socketClient;
    private void initSocketClient() {
        socketClient = new SocketClient("192.168.1.100", 502);
        socketClient.setSocketListener(new SocketClient.SocketListener() {

            @Override
            public void onMessageReceived(byte[] data) {
                receiveData = CommonUtils.ArrayAppend(receiveData, data, data.length);
            }

            @Override
            public void onStatusChanged(boolean isConnected) {

            }
        });
        socketClient.connect();
    }

    byte[] receiveData = null;
    public byte[] sendAndReceive(byte[] sendData)
    {
        try {
            // 发送示例数据
            receiveData = null;
            socketClient.sendData(sendData);
            int index = 0;
            while( index < 100)
            {
                if(check())
                {
                    return receiveData.clone();
                }
                SystemClock.sleep(5);
                index++;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private boolean check()
    {
        if(receiveData != null )
        {
            Log.d("SHOOTLEESCOKET","CHECK,长度："+receiveData.length+"||"+CommonUtils.ByteArrayToHexString(receiveData));
            return true;
        }
        return false;
    }
}
